import { _decorator, Component, ScrollView, UITransform, v2, Vec2 } from 'cc';
const { ccclass, property } = _decorator;

export var GLOBAL_MAP_NAME;

@ccclass('RuntimeScrollSaverSimple')
export default class RuntimeScrollSaverSimple extends Component {
    public static Instance: RuntimeScrollSaverSimple;

    @property({ type: ScrollView, tooltip: '若不填组件会自动在当前节点/子节点查找 ScrollView' })
    public scrollView: ScrollView | null = null;

    private _acc = 0;
    saveInterval = 0.4;

    onLoad() {
        RuntimeScrollSaverSimple.Instance = this;

        this.scheduleOnce(() => {
            this.读取();
        }, 0.01);
    }

    保存() {
        const y = this.scrollView.getScrollOffset().y;
        GLOBAL_MAP_NAME = y;
    }

    读取() {
        let y = GLOBAL_MAP_NAME;
        console.log(`GLOBAL_MAP_NAME`, GLOBAL_MAP_NAME)
        this.scrollView.scrollToOffset(new Vec2(0, y), 0, true);
    }

    update(dt: number) {
        // if (!this.scrollView) return;
        this._acc += dt;
        if (this._acc >= this.saveInterval) {
            this._acc = 0;
            this.保存();
        }
    }
}